package com.mytwitter.acitivity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class takingVideoRecord extends Activity {
        private File myRecAudioFile;
        private SurfaceView msurfaceview;
        private SurfaceHolder msurfaceholder;
        private Button buttonstart;
        private Button buttonfinish;
        private File dir;
        private MediaRecorder recorder;
        private Camera camera;
        String useremail = LoginActivity.ReturnUserEmail();//获取用户email

        myDatabaseHelper myhelper;//数据库操作实例
        SQLiteDatabase db ;
        myTabOperate operate;

        String currenttime;//保存当前时间
        String path;
        String outputfile;
        
        public void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
                setContentView(R.layout.takingvideo);
                
                myhelper = new myDatabaseHelper(this);
                db = myhelper.getWritableDatabase();//打开数据库
                operate = new myTabOperate(this.db);//获得数据库对象的操作的实例

                File defaultDir = Environment.getExternalStorageDirectory();//获取外设目录；File.separator是插入“\”
 				path = defaultDir.getAbsolutePath()+File.separator+"VlogVideo"+File.separator;
 				 				
                msurfaceview = (SurfaceView)findViewById(R.id.takingvideo_camara);
                camera = Camera.open();
                try {
					camera.setPreviewDisplay(msurfaceholder);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
                
//                msurfaceholder = msurfaceview.getHolder();
//                msurfaceholder.addCallback(this);
//                msurfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                buttonstart = (Button)findViewById(R.id.takingvideo_btStart);
                buttonfinish = (Button)findViewById(R.id.takingvideo_btfinish);
                buttonfinish.setEnabled(false);//刚开始不可用
                File defaultDir2 = Environment.getExternalStorageDirectory();//获取外设目录；File.separator是插入“\”
                //创建文件夹存放视频
                String path = defaultDir2.getAbsolutePath()+File.separator+"VlogVideo"+File.separator;
                dir = new File(path);
                if(!dir.exists()){//不存在这样的文件夹，则创建
                        dir.mkdirs();
                }
               
                buttonstart.setOnClickListener(new OnClickListener() {
                        public void onClick(View v){
                        	//获取时间记录
                                try{
                                		//此时间存数据库
                                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
                                        Date curdata = new Date(System.currentTimeMillis());//获取当前时间
                                        currenttime = formatter.format(curdata);
                                        
                                }catch(Exception e){
                                        System.out.println("Error:"+e);
                                }
                               // setCameraDisplayOrientation(takingVideoRecord.this,null,camera);
                                recorder();//录像
                                buttonstart.setEnabled(false);
                                buttonfinish.setEnabled(true);//可用
                        }
                });
                buttonfinish.setOnClickListener(new OnClickListener(){
                        public void onClick(View v){
                                recorder.stop();//停止录像
                                recorder.reset();
                                recorder.release();//释放资源
                                recorder = null;
                                buttonstart.setEnabled(true);//¿ÉÓÃ
                                buttonfinish.setEnabled(false);//²»¿ÉÓÃ
 //                               camera.lock();
                                camera.stopPreview();
                                camera.release();
                                
                                
//                              //插入一条记录
                                String[] namestr = new String[5];
                                operate.insert(outputfile, useremail, currenttime, 0, 0);
//                                                                
                                final String strname = namestr[4];
//                                Tipstoupload(strname);                           
                        }
                });
        }
        
       public void Tipstoupload(final String strname)
       {
           //弹框显示是否上传
           AlertDialog.Builder uploaddialog = new AlertDialog.Builder(takingVideoRecord.this);
           uploaddialog.setTitle("提示");
           uploaddialog.setMessage("现在上传吗？");
           uploaddialog.setPositiveButton("确定", new DialogInterface.OnClickListener(){
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                          // TODO Auto-generated method stub
                	   	   String str2 = "";
                           upload uploadnow = new upload();
                           uploadnow.uploadvideo(strname,str2);
                   }
           })
           .setNegativeButton("取消", null);
           uploaddialog.create();
           uploaddialog.show(); 
       }
       
        @Override
        protected void onResume() {
                super.onResume();
        }
        
        public void recorder(){
                try {
                		Random rand = new Random();
                		String number1 = String.valueOf((rand.nextInt(90000)+10000));
                		String number2 = String.valueOf((rand.nextInt(90000)+10000));
                		outputfile = number1+number2+".avi";
                		
                		camera.startPreview();
                		recorder = new MediaRecorder();//实例化
                		camera.unlock();
                		recorder.setCamera(camera);
                		
                        recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频源
                        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//录音源为麦克风
                        recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
                      
                        recorder.setOutputFile(path+outputfile);//保存路径
                        recorder.setPreviewDisplay(msurfaceview.getHolder().getSurface());
                        
                        recorder.prepare();
                        recorder.start();//开始录像
                        
                }catch (IllegalStateException e) {
                    System.out.print("33");
                	e.printStackTrace();
                }
                catch (IOException e) {
                	System.out.print("9999");    
                	e.printStackTrace();
                }               
        }
}
